import { UpdateInfo, UpdaterEvents } from 'electron-updater'
import { ref, Ref } from 'vue'
import { useUa } from './ua'

function isUpdateAvailable(cmd: UpdaterEvents, data: AutoUpdaterMessage['message']): data is UpdateInfo {
  return cmd === 'update-available'
}

function updateAvailable(data: AutoUpdaterMessage, info: Ref<UpdateInfo | null>) {
  if (isUpdateAvailable(data.cmd, data.message)) {
    info.value = data.message
  }
}

export function useUpdate() {
  const ua = useUa()
  const visible = ref(false)
  const data = ref<null | UpdateInfo>(null)

  if (ua.isClient.value) {
    API.onUpdater(function (message) {
      switch (message.cmd) {
        case 'update-available':
          updateAvailable(message, data)
          visible.value = true
          break
        default:
          break
      }
    })
  }

  return {
    data,
    visible,
    now() {
      API.updateNow()
    }
  }
}
